package com.z_talk.server.localization;

import com.z_talk.core.model.LoginModel;
import com.z_talk.core.model.UserInfo;
import com.z_talk.core.util.FileUtil;
import com.z_talk.server.config.PropertiesUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 操作用户信息，保存文件，文件中读取等操作
 */
public class UserLocalzation {

    public static UserInfo userLogin(LoginModel loginVO) throws IOException, ClassNotFoundException {
        AtomicReference<UserInfo> userInfo = new AtomicReference<>();
        List<UserInfo> list = loadUserList();
        list.forEach(item -> {
            if (item.getUserId().equals(loginVO.getUserId())&&item.getPassword().equals(loginVO.getPassword())){
                userInfo.set(item);
            }
        });
        return userInfo.get();
    }

    public static List<UserInfo> loadUserList()  {
        try {
            String filePath = PropertiesUtil.configProp.getProperty("filePath");
            String fileName = PropertiesUtil.configProp.getProperty("userFile");
            File file = FileUtil.createFile(filePath+fileName);
            InputStream in = new FileInputStream(file);
            ObjectInputStream objectInputStream = new ObjectInputStream(in);
            List<UserInfo> list = (List<UserInfo>)objectInputStream.readObject();
            return list;
        }catch (EOFException e){
            return new ArrayList<>();
        }catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean saveUser(List<UserInfo> users){
        ObjectOutputStream oos = null;
        try {
            String filePath = PropertiesUtil.configProp.getProperty("filePath");
            String fileName = PropertiesUtil.configProp.getProperty("userFile");
            File file = FileUtil.createFile(filePath+fileName);
            oos = new ObjectOutputStream(
                    new FileOutputStream(file));
            //写回用户信息
            oos.writeObject(users);
            oos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally{
            if(null != oos){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        List<UserInfo> list = loadUserList();
        System.out.println(list);
    }





}
